package com.huc.cog;

import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @auther huc
 * @date 2020/8/25 0025 AM 9:20
 */
@Component
@EnableAsync
public class AnnotationAsyncConfig implements AsyncConfigurer {

    /**
     * 线程池维护线程的最小数量
     */
    private int corePoolSize = 2;
    /**
     * 线程池维护线程的最大数量
     */
    private int maxPoolSize = 2;
    /**
     * 队列最大长度
     */
    private int queueCapacity = 100;
    /**
     * 获取异步线程池执行对象
     */
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("async-thread-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //拒绝策略 CallerRunsPolicy 由调用线程处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
